import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.less']
})
export class SignupComponent implements OnInit {

  public signForm:{
    email:string,
    password:string
  } = {
    email:'',
    password:''
  }

  public email_err_msg:string = '';
  constructor(private http:HttpClient,private router:Router) { }

  ngOnInit() {
  }

  signUpHandler(){
    this.http.post('http://localhost:3000/users',this.signForm)
      .toPromise()
      .then( (res:any)=>{
        this.email_err_msg = '';
        window.localStorage.setItem('auth_token',res.token);
        window.localStorage.setItem('userInfo',JSON.stringify(res.user));
        this.router.navigate(['/']);
      })
      .catch(err=>{
        if(err.status==409){
          this.email_err_msg = '邮箱已被占用'
        }
      })
  }

}
